package com.training.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.training.common.Result;
import com.training.common.TrainingPage;
import com.training.common.model.*;
import com.training.common.model.Class;
import com.training.service.*;

import java.util.*;

public class TrainController extends Controller {

    @Inject(TrainServiceImp.class)
    private TrainService trainService;

    @Inject(ClassServiceImp.class)
    private ClassService classService;

    @Inject(SubjectServiceImp.class)
    private SubjectService subjectService;

    @Inject(StudentServiceImp.class)
    private StudentService studentService;

    public void index(){
        render("/views/train/index.html");
    }

    public void getTrainPage(){
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        String name = getPara("name");
        Page<Train> trainPage = trainService.getTrainPage(pageNumber,pageSize,name);
        Result result = new Result();
        result.setData(new TrainingPage(trainPage));
        renderJson(result);
    }

    public void showTrain(){
        List<Class> classList = classService.getClassAllList();
        List<Subject> subjectList = subjectService.getSubjectList();
        if(getPara("id")==null){
            setAttr("classList",classList);
            setAttr("subjectList",subjectList);
            render("/views/train/add.html");
        }else{
            String id = getPara("id");
            setAttr("id",id);
            Train train = Train.dao.findById(id);
            String[] classids = train.getClassids().split(",");
            List<Class> edClassList = new ArrayList<Class> ();
            for(Class aclass : classList){
                for(String tedclassid : classids){
                    if(aclass.getId() == Integer.parseInt(tedclassid)){
                        aclass.put("selected","selected=\"selected\"");
                    }
                }
                edClassList.add(aclass);
            }
            setAttr("classList",edClassList);

            String[] subjectids = train.getSubjectids().split(",");
            List<Subject> subjectList1 = new ArrayList<Subject> ();
            for (Subject subject : subjectList){
                for (String subjectid : subjectids){
                    if(subject.getId() == Integer.parseInt(subjectid)){
                        subject.put("selected","selected=\"selected\"");
                    }
                }
                subjectList1.add(subject);
            }
            setAttr("subjectList",subjectList1);
            render("/views/train/edit.html");
        }

    }

    @Before(Tx.class)
    public void addTrain(){
        String name = getPara("name");
        String classids = getPara("classids");
        String subjectids = getPara("subjectids");
        Train train = new Train();
        train.setName(name);
        User user = getSessionAttr("trainingsession");
        train.setUserId(user.getID());
        train.setCreatetime(new Date());
        train.setClassids(classids);
        train.setSubjectids(subjectids);
        boolean boo = train.save();
        Result result = new Result();
        if(boo){
            result.setErrorNo(0);
            result.setErrorInfo("添加成功！");
        }else{
            result.setErrorNo(500);
            result.setErrorInfo("添加失败！");
        }
        renderJson(result);
    }

    public void getTrain(){
        String id = getPara("id");
        Train train = Train.dao.findById(id);
        Result result = new Result();
        result.setData(train);
        renderJson(result);
    }

    @Before(Tx.class)
    public void editTrain(){
        String id = getPara("id");
        String name = getPara("name");
        String classids = getPara("classids");
        String subjectids = getPara("subjectids");
        Result result = new Result();
        Train train = Train.dao.findById(id);
        train.setName(name);
        train.setClassids(classids);
        train.setSubjectids(subjectids);
        boolean boo = train.update();

        if (boo) {
            result.setErrorNo(0);
            result.setErrorInfo("更新成功！");
        } else {
            result.setErrorNo(500);
            result.setErrorInfo("更新失败！");
        }
        renderJson(result);
    }

    @Before(Tx.class)
    public void deleteTrain(){
        String ids = getPara("id");
        String[] idss = ids.split(",");
        Result result = new Result();
        boolean boo = false;
        for (String id : idss){
            int idi = Integer.parseInt(id);
            boo = Train.dao.deleteTrain(idi);
        }
        if(boo){
            result.setErrorNo(0);
            result.setErrorInfo("删除成功！");
        }else{
            result.setErrorNo(500);
            result.setErrorInfo("删除失败！");
        }
        renderJson(result);
    }

    public void showTrainResult(){
        String id = getPara("id");
        Train train = Train.dao.findById(id);
        List<Subject> subjectList = subjectService.getTrainSubjectList(train.getSubjectids());
        setAttr("subjectList",subjectList);
        setAttr("train_id",id);
        render("/views/train/showresult.html");
    }

    public void getTrainResultPage(){
        int train_id = getParaToInt("train_id");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        String number = getPara("number");
        String name = getPara("name");
        Page<Student> trainResultPage = trainService.getTrainResultPage(train_id,pageNumber,pageSize,number,name);
        Result result = new Result();
        result.setData(new TrainingPage(trainResultPage));
        renderJson(result);
    }

    public void showEditTrainResult(){
        String newid = getPara("newid");
        String[] newids = newid.split("-");
        Student student = Student.dao.findById(newids[1]);
        Train train = Train.dao.findById(newids[0]);
        List<Subject> subjectList = subjectService.getTrainSubjectList(train.getSubjectids());
        List<Subject> subjectnewList = new ArrayList<Subject>();
        for(Subject subject : subjectList){
            com.training.common.model.Result resultmodel = com.training.common.model.Result.dao.getTrainResult(Integer.parseInt(newids[0]),subject.getId(),student.getClassId(),student.getId());
            String result = "";
            if(resultmodel!=null){
                result = resultmodel.getResult();
            }
            subject.put("result",result);
            subjectnewList.add(subject);
        }
        setAttr("newid",newid);
        setAttr("student",student);
        setAttr("subjectList",subjectnewList);
        render("/views/train/showEditTrainResult.html");
    }

    @Before(Tx.class)
    public void addTrainResult(){
        String newid = getPara("newid");
        String[] newids = newid.split("-");
        Student student = Student.dao.findById(newids[1]);
        Train train = Train.dao.findById(newids[0]);
        User user = getSessionAttr("trainingsession");
        Map<String, String[]> resultmap = getParaMap();
        boolean deleteboo = trainService.deleteTrainResult(newids);
        com.training.common.model.Result result = null;
        boolean boo = true;
        for (Map.Entry<String, String[]> entry : resultmap.entrySet()) {
            if(!entry.getKey().equals("newid")){
                result = new com.training.common.model.Result();
                result.setTrainId(Integer.parseInt(newids[0]));
                result.setSubjectId(Integer.parseInt(entry.getKey()));
                result.setClassId(student.getClassId());
                result.setStudentId(student.getId()+"");
                result.setResult(entry.getValue()[0]);
                result.setUserId(user.getID());
                result.setCreatetime(new Date());
                boo = result.save();
            }
        }
        Result returnresult = new Result();

        if(boo&&deleteboo){
            returnresult.setErrorNo(0);
            returnresult.setErrorInfo("修改成功！");
        }else{
            returnresult.setErrorNo(500);
            returnresult.setErrorInfo("修改失败！");
        }
        renderJson(returnresult);
    }

    @Before(Tx.class)
    public void deleteTrainResult(){
        String newid = getPara("newid");
        String[] newids = newid.split("-");
        boolean deleteboo = trainService.deleteTrainResult(newids);
        Result returnresult = new Result();
        if(deleteboo){
            returnresult.setErrorNo(0);
            returnresult.setErrorInfo("清空成功！");
        }else{
            returnresult.setErrorNo(500);
            returnresult.setErrorInfo("清空失败！");
        }
        renderJson(returnresult);
    }

    public void getTrainList(){
        int pageNumber = 1;
        int pageSize = 100;
        String name = getPara("name");
        Page<Train> trainPage = trainService.getTrainPage(pageNumber,pageSize,name);
        List<Train> trainList = trainPage.getList();
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("code",0);
        dataMap.put("msg","success");
        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
        Map<String,Object> map = null;
        for(Train train : trainList){
            map = new HashMap<String,Object>();
            map.put("name",train.getName());
            map.put("value",train.getId());
            data.add(map);
        }
        dataMap.put("data",data);
        renderJson(dataMap);
    }

    public void getTrainStudentList(){
        String trainid = getPara("trainid");
        Map<String,Object> dataMap = new HashMap<String,Object>();
        renderJson(dataMap);
        if(trainid == null){
            dataMap.put("code",0);
            dataMap.put("msg","success");
            dataMap.put("data","");
        }else{
            Train train = Train.dao.findById(trainid);
            Page<Student> studentPage = studentService.getStudentTrainPage(train.getClassids(),1, 100, null,null);
            List<Student> studentList = studentPage.getList();
            dataMap.put("code",0);
            dataMap.put("msg","success");
            List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
            Map<String,Object> map = null;
            for(Student student : studentList){
                map = new HashMap<String,Object>();
                map.put("name",student.getName());
                map.put("value",student.getId());
                data.add(map);
            }
            dataMap.put("data",data);
        }
        renderJson(dataMap);
    }

    public void showTrainInsert(){
        render("/views/train/showTrainInsert.html");
    }

    public void getTrainListsubjectid(){
        String subjectid = getPara("subjectid");
        List<Train> trainList = Train.dao.getTrainListsubjectid(subjectid);
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("code",0);
        dataMap.put("msg","success");
        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
        Map<String,Object> map = null;
        for(Train train : trainList){
            map = new HashMap<String,Object>();
            map.put("name",train.getName());
            map.put("value",train.getId());
            data.add(map);
        }
        dataMap.put("data",data);
        renderJson(dataMap);
    }

}
